//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by QUAN on 15/11/9.
//  Copyright © 2015年 QUAN. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        //验证归档中的文件
        let account = ZZUserAccount.loadAccount()
        print(account)
        
        //初始化窗口
        window = UIWindow(frame: UIScreen.mainScreen().bounds)

        //设置根控制器
        window?.rootViewController = defaultRootController()
        
        window?.backgroundColor = UIColor.whiteColor()
        
        registerNotification()
        
        //设置主色调
        setThemeColor()
        
        //让窗口可见
        window?.makeKeyAndVisible()
        return true
    }
    
    //监听通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewControler, object: nil)
    }
    
    @objc private func switchToRootVC(not: NSNotification) {
        print(not)
        //如果通知传回来东西,就执行下面代码, 注册完成后
        if(not.object as? String) != nil {
            window?.rootViewController = ZZWelComeController()
            return
        }
        window?.rootViewController = ZZMainController()
    }
    
    private func defaultRootController() -> UIViewController {
        if ZZUserAccountViewModel().userLogin {
        
            return isNewVersion() ? ZZNewFeatureViewController() : ZZWelComeController()
        }
        return ZZMainController()
    }
    
    //检测是否是新版本
    private func isNewVersion() -> Bool{
        //获取新版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionStr)
        print(versionNum)
        
        let key = "sandBoxKey"
        
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        print(lastVersion)
        
        userdefaults.setDouble(versionNum!, forKey: key)
        
        userdefaults.synchronize()
        
        return versionNum! > lastVersion
    }
    
    //设置主色调
    private func setThemeColor() {
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }

}

